package com.pragati.jjcet.alumni;

import java.io.IOException;
import java.util.Date;
import java.util.StringTokenizer;

import javax.servlet.http.*;
import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;
import com.pragati.util.myUtil;
import com.pragati.jjcet.alumni.Alumni;
import com.pragati.jjcet.alumni.Hits;
import com.pragati.jjcet.alumni.PMF;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import java.util.List;

@SuppressWarnings("serial")
public class JjcetalumniServlet extends HttpServlet {
	private String msgBody = null;
	boolean messageSent = false;
	boolean success = false;
	Message msg = null;
	XMPPService xmpp = null;

	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		// String msgBody =null;
		String alumni = null;
		myUtil mu = new myUtil();
		String greeting = mu.Greeter();
		xmpp = XMPPServiceFactory.getXMPPService();
		Message message = xmpp.parseMessage(req);

		JID fromJid = message.getFromJid();
		String body = message.getBody();
		String name = fromJid.getId();
		name = name.substring(0, name.indexOf("@"));

		Hits hit = new Hits(name, fromJid.getId(), new Date());

		PersistenceManager pm = PMF.get().getPersistenceManager();

		try {
			pm.makePersistent(hit);
		} finally {
			pm.close();
		}

		if (body.equalsIgnoreCase("help")) {
			setMsgBody("Help \nYou can try the following commands ");

			success = sendMsg(fromJid);
			setMsgBody("-----------------------------");
			success = sendMsg(fromJid);
			setMsgBody("getphone <firstname>  (lowercase only)");
			success = sendMsg(fromJid);
			setMsgBody("listall (To list all the name in database)");
			// ravi,kumar,+919810269308
			success = sendMsg(fromJid);
			setMsgBody("setdata <firstname>,<lastname>,<phone-number> ");
			success = sendMsg(fromJid);
			setMsgBody("eg., setdata ravi,kumar,+91981xxxxxxx");
			success = sendMsg(fromJid);
			setMsgBody("-----------------------------");
			success = sendMsg(fromJid);
			setMsgBody("http://jjcet-alumni.appspot.com/");
			success = sendMsg(fromJid);
		} else if (body.contains("Hi")) {
			setMsgBody(greeting
					+ " "
					+ name
					+ ",\n How can I Help you ?.. you can try typing 'help' to start with");
			success = sendMsg(fromJid);
		} else if (body.contains("getphone")) {
			PersistenceManager pmm = PMF.get().getPersistenceManager();
			alumni = body.substring(9, body.length());
			alumni = alumni.toLowerCase();
			setMsgBody("So you want the phone number for  " + alumni);

			success = sendMsg(fromJid);
			Query query = pmm.newQuery(Alumni.class,
					"firstName == firstNameParam && approved == 'Y'");
			query.setFilter("firstName == firstNameParam");
			query.setOrdering("firstName asc");
			query.declareParameters("String firstNameParam");

			try {
				List<Alumni> results = (List<Alumni>) query.execute(alumni);
				if (results.iterator().hasNext()) {
					for (Alumni e : results) {
						setMsgBody("Phone number of " + e.getFirstName() + " "
								+ e.getLastName() + " is :" + e.getCellPhone());
						success = sendMsg(fromJid);
					}
				} else {
					setMsgBody("Sorry name not in Database ");
					success = sendMsg(fromJid);
					setMsgBody("http://jjcet-alumni.appspot.com/");
					success = sendMsg(fromJid);
				}
			} finally {
				query.closeAll();
			}
		} else if (body.contains("listall")) {
			PersistenceManager pmm = PMF.get().getPersistenceManager();
			// alumni=body.substring(9,body.length());
			setMsgBody("So you want the phone number for  all");
			success = sendMsg(fromJid);
			Query query = pmm.newQuery(Alumni.class, "approved == 'Y'");

			// query.setFilter("approved == 'Y'");
			// query.setFilter("firstName == firstNameParam");
			query.setOrdering("firstName asc");
			// query.declareParameters("String firstNameParam");

			try {
				List<Alumni> results = (List<Alumni>) query.execute();
				if (results.iterator().hasNext()) {
					for (Alumni e : results) {
						setMsgBody("Phone number of " + e.getFirstName() + " "
								+ e.getLastName() + " is :" + e.getCellPhone());
						success = sendMsg(fromJid);
					}
				} else {
					setMsgBody("Sorry name not in Database ");
					success = sendMsg(fromJid);

				}
			} finally {
				query.closeAll();
			}
			setMsgBody("http://jjcet-alumni.appspot.com/");
			success = sendMsg(fromJid);

		}

		else if (body.contains("listhits")) {
			PersistenceManager pmm = PMF.get().getPersistenceManager();
			// alumni=body.substring(9,body.length());
			setMsgBody("List of all access till now!!!");
			success = sendMsg(fromJid);
			Query query = pmm.newQuery(Hits.class);
			// query.setFilter("firstName == firstNameParam");
			// query.setOrdering("firstName asc");
			// query.declareParameters("String firstNameParam");

			try {
				List<Hits> results = (List<Hits>) query.execute();
				if (results.iterator().hasNext()) {
					for (Hits e : results) {
						setMsgBody("" + e.getEmailId() + "," + e.getJid() + ","
								+ e.getHitDate());
						success = sendMsg(fromJid);
					}
				} else {
					setMsgBody("Sorry no entry Database ");
					success = sendMsg(fromJid);

				}
			} finally {
				query.closeAll();
			}
			setMsgBody("Visit me at: http://www.firststop.in/");
			success = sendMsg(fromJid);

		} else if (body.contains("setdata")) {
			String temp = body.substring(8, body.length());
			// ravi,kumar,+919810269308
			String fname = null, lname = null, celno = null;
			StringTokenizer st = null;
			st = new StringTokenizer(temp, ",");
			while (st.hasMoreTokens()) {
				if (st.hasMoreTokens())
					fname = st.nextToken();
				if (st.hasMoreTokens())
					lname = st.nextToken();
				if (st.hasMoreTokens())
					celno = st.nextToken();
			}
			setMsgBody("Setting " + fname + " " + lname + ":" + celno);
			success = sendMsg(fromJid);
			if (fname != null && lname != null && celno != null) {
				fname = fname.toLowerCase();
				Alumni alumnii = new Alumni(fname, lname, celno, "1", "N",
						new Date());

				PersistenceManager pmm = PMF.get().getPersistenceManager();

				try {
					pmm.makePersistent(alumnii);
				} finally {
					pmm.close();
				}

				setMsgBody("Data set successfully (But will not be visible untill approved by bot-owner!!!");
			} else {
				setMsgBody("Data format incorrect !!!");
			}
			success = sendMsg(fromJid);
		} else {
			setMsgBody("I am sorry can you re-phrase your question or type 'help' to view the available keywords");
			success = sendMsg(fromJid);
			setMsgBody("Visit me at: http://www.firststop.in/");
			success = sendMsg(fromJid);
		}

	}

	@SuppressWarnings("deprecation")
	public boolean sendMsg(JID toJid) {
		msg = new MessageBuilder().withRecipientJids(toJid).withBody(
				getMsgBody()).build();
		if (xmpp.getPresence(toJid).isAvailable()) {
			SendResponse status = xmpp.sendMessage(msg);
			messageSent = (status.getStatusMap().get(toJid) == SendResponse.Status.SUCCESS);
		}
		return messageSent;
	}

	public void setMsgBody(String msgBody) {
		this.msgBody = msgBody;
	}

	public String getMsgBody() {
		return msgBody;
	}
}